package com.vay.de.dang.online.util;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import java.util.ArrayList;
import java.util.List;

import com.vay.de.dang.online.VnApp;
import com.vay.de.dang.online.resp.RFinancialProductDto;
import com.vay.de.dang.online.ui.BaseActivity;
import com.vay.de.dang.online.ui.apply.Step1Activity;
import com.vay.de.dang.online.ui.sign.SignInActivity;
import com.vay.de.dang.online.web.LoanApi;
import com.vay.de.dang.online.web.ReqResult;
import com.vay.de.dang.online.R;
import com.vay.de.dang.online.entiy.EmergencyContactsEntity;
import com.vay.de.dang.online.entiy.AppConfigEntity;
import com.vay.de.dang.online.entiy.IncomeRequestEntity;
import com.vay.de.dang.online.entiy.CommodityEntity;
import com.vay.de.dang.online.entiy.PropertyRuleEntity;
import com.vay.de.dang.online.entiy.RuleNotEmptyEntity;
import com.vay.de.dang.online.entiy.RuleRegexpEntity;
import com.vay.de.dang.online.entiy.RuleStringLengthEntity;
import com.vay.de.dang.online.resp.RCodeTableDto;
import com.vay.de.dang.online.resp.RCustomerDataDto;
import com.vay.de.dang.online.resp.REmergencyContactDto;
import com.vay.de.dang.online.web.DeviceApi;
import com.vay.de.dang.online.web.ReqCallback;
import com.vay.de.dang.online.view.DialogInstructions;

public class RequestHelper {

    private static List<PropertyRuleEntity> baseRuleList;
    private static List<PropertyRuleEntity> idRuleList;

    // 紧急联系人
    private static IncomeRequestEntity request;
    public static List<EmergencyContactsEntity> emergencyContactsList = new ArrayList<>();

    // 必要联系人
    public static List<EmergencyContactsEntity> essentialContactsList = new ArrayList<>();

    public static String currentCommodityNum;
    public static String currentCommodityName;
    public static List<RFinancialProductDto> products;

    // 首贷
    public static void clickApply(BaseActivity activity, CommodityEntity entity) {
        // 设备权限校验
        /*if (!PermissionUtil.checkPermission(activity, PermissionUtil.getAllPermission())) {
            PermissionUtil.requestAll(activity, (allGranted, grantedList, deniedList) -> {
                if (allGranted) {
                    nextApply(activity, entity);
                } else {
                    activity.showHint(R.string.error_permission_apply);
                }
            });
        } else {
            nextApply(activity, entity);
        }*/

        nextApply(activity, entity);
    }

    private static void nextApply(BaseActivity activity, CommodityEntity entity) {
        emergencyContactsList.clear();
        essentialContactsList.clear();

        // next
        if (VnContext.instance().isLogin()) {

            // 配置文件
            AppConfigEntity config = VnContext.instance().getAppConfig();
            if (config == null) {
                activity.showHint("Please Wait, Initializing...");
                return;
            }
            int numberOfEmergency = config.getNumberOfEmergencyContacts();

            // 紧急联系人
            List<EmergencyContactsEntity> emergencyContacts = RequestHelper.emergencyContactsList;
            emergencyContacts.clear();
            for (int i = 0; i < numberOfEmergency; i++) {
                emergencyContacts.add(new EmergencyContactsEntity());
            }

            // 送审手机号码
            if (config.isGpPhone()) {
                new DialogInstructions(activity).showPermission(() -> {
                    if (!PermissionUtil.checkPermission(activity, PermissionUtil.getApplyPermission())) {
                        PermissionUtil.requestAll(activity, (allGranted, grantedList, deniedList) -> {
                            if (allGranted) {
                                requestApplyActivity(activity, entity.getCommodityName(), entity.getCommodityNum());
                            } else {
                                activity.showHint(R.string.error_permission_apply);
                            }
                        });
                    } else {
                        requestApplyActivity(activity, entity.getCommodityName(), entity.getCommodityNum());
                    }
                });
            } else {
                if (!PermissionUtil.checkPermission(activity, PermissionUtil.getApplyPermission())) {
                    PermissionUtil.requestAll(activity, (allGranted, grantedList, deniedList) -> {
                        if (allGranted) {
                            requestApplyActivity(activity, entity.getCommodityName(), entity.getCommodityNum());
                        } else {
                            activity.showHint(R.string.error_permission_apply);
                            //gotoSetting(activity);
                        }
                    });
                } else {
                    requestApplyActivity(activity, entity.getCommodityName(), entity.getCommodityNum());
                }
            }
        } else {
            Intent intent = new Intent();
            intent.setClass(activity, SignInActivity.class);
            intent.putExtra("applyNo", entity.getCommodityNum());
            activity.startActivity(intent);
        }
    }

    private static void gotoSetting(BaseActivity activity) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT == 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", activity.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", activity.getPackageName());
        } else {
            intent.setAction(Settings.ACTION_SETTINGS);
        }
        activity.startActivity(intent);
    }

    public static String checkPhoneRepeat(String phone) {
        List<EmergencyContactsEntity> all = new ArrayList<>();
        if (emergencyContactsList != null) all.addAll(emergencyContactsList);
        all.addAll(essentialContactsList);

        for (EmergencyContactsEntity ec : all) {
            String str = ec.getContactPhone();
            if (!VnUtil.isEmpty(str) && str.equals(phone)) {
                return VnApp.getStr(R.string.error_emergency_contract);
            }
        }

        return null;
    }

    public static void queryCustomerData(BaseActivity activity, boolean showDialog,
                                         OnCustomerDataCallback callback) {
        LoanApi.queryCustomerData(new ReqCallback(activity) {
            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {

                    IncomeRequestEntity incomeRequest = RequestHelper.currentIncome();

                    // 基本信息
                    RCustomerDataDto dto = ResponseHelper.customerData;
                    if (dto != null) {
                        RCodeTableDto p = dto.getResidentialAddressProvince();
                        RCodeTableDto c = dto.getResidentialAddressCity();
                        RCodeTableDto r = dto.getResidentialAddressArea();
                        if (p != null && c != null && r != null) {
                            incomeRequest.setResidentialAddressProvince(p.getValue());
                            incomeRequest.setResidentialAddressCity(c.getValue());
                            incomeRequest.setResidentialAddressArea(r.getValue());
                        }
                        incomeRequest.setResidentialAddress(dto.getResidentialAddress());

                        // 居住时长
                        RCodeTableDto tableDto = dto.getResidenceTimeLength();
                        if (tableDto != null) {
                            incomeRequest.setResidenceTimeLength(tableDto.getValue());
                        }

                        // 性别
                        tableDto = dto.getSex();
                        if (tableDto != null) {
                            incomeRequest.setSex(VnUtil.toIntValue(tableDto.getValue()));
                        }

                        // 生日
                        incomeRequest.setBirthTime(dto.getBirthTime());

                        // 教育
                        tableDto = dto.getHighestEducation();
                        if (tableDto != null) {
                            incomeRequest.setHighestEducation(tableDto.getValue());
                        }

                        // 婚姻
                        tableDto = dto.getMaritalStatus();
                        if (tableDto != null) {
                            incomeRequest.setMaritalStatus(tableDto.getValue());
                        }

                        // 子女
                        tableDto = dto.getChildrenNumber();
                        if (tableDto != null) {
                            incomeRequest.setChildrenNumber(tableDto.getValue());
                        }

                        // facebook
                        incomeRequest.setFacebook(dto.getFacebook());
                        // email
                        incomeRequest.setEmail(dto.getEmail());

                        // 配置文件
                        AppConfigEntity config = VnContext.instance().getAppConfig();
                        int numberOfEmergency = config.getNumberOfEmergencyContacts();

                        // 紧急联系人
                        List<EmergencyContactsEntity> emergencyContacts = RequestHelper.emergencyContactsList;

                        // 非必要联系人
                        List<EmergencyContactsEntity> essentialContacts = RequestHelper.essentialContactsList;
                        essentialContacts.clear();

                        // 紧急联系人
                        List<REmergencyContactDto> list = ResponseHelper.emergencyContact;
                        int size = list.size();
                        if (!VnUtil.isEmpty(list) && size >= numberOfEmergency) {

                            // 更新紧急联系人
                            for (int i = 0; i < numberOfEmergency; i++) {
                                REmergencyContactDto c0 = list.get(i);
                                emergencyContacts.set(i, RequestHelper.toEmergencyContactsByDto(c0));
                            }

                            // 更新
                            if (size > numberOfEmergency) {
                                for (int index = numberOfEmergency; index < size; index++) {
                                    EmergencyContactsEntity ec = RequestHelper.toEmergencyContactsByDto(list.get(index));
                                    essentialContacts.add(ec);
                                }
                            }
                        }

                        // 其他属性
                        incomeRequest.setCompanyName(dto.getCompanyName());
                        incomeRequest.setCompanyPhone(dto.getCompanyPhone());

                        // 职业
                        tableDto = dto.getPost();
                        if (tableDto != null) {
                            incomeRequest.setPost(tableDto.getValue());
                        }

                        // 月收入
                        tableDto = dto.getWorkIncome();
                        if (tableDto != null) {
                            incomeRequest.setWorkIncome(VnUtil.toIntValue(tableDto.getValue()));
                        }

                        // 工作年限
                        tableDto = dto.getWorkTimeLength();
                        if (tableDto != null) {
                            incomeRequest.setWorkTimeLength(VnUtil.toIntValue(tableDto.getValue()));
                        }

                        // 第一发薪日
                        tableDto = dto.getOnePayday();
                        if (tableDto != null) {
                            incomeRequest.setOnePayday(tableDto.getValue());
                        }

                        // 第二发薪日
                        tableDto = dto.getPayday();
                        if (tableDto != null) {
                            incomeRequest.setPayday(VnUtil.toIntValue(tableDto.getValue()));
                        }

                        // 收款类型
                        tableDto = dto.getWithdrawalType();
                        if (tableDto != null) {
                            incomeRequest.setWithdrawalType(VnUtil.toIntValue(tableDto.getValue()));
                        }

                        // 收款方式
                        tableDto = dto.getWithdrawalMethod();
                        if (tableDto != null) {
                            incomeRequest.setWithdrawalMethod(tableDto.getValue());
                        }

                        // name
                        incomeRequest.setFirstName(dto.getFirstName());
                        incomeRequest.setMiddleName(dto.getMiddleName());
                        incomeRequest.setLastName(dto.getLastName());

                        // 证件类型
                        tableDto = dto.getIdType();
                        if (tableDto != null) {
                            incomeRequest.setIdType(tableDto.getValue());
                        }

                        // 证件号码
                        incomeRequest.setIdNumber(dto.getIdNumber());

                        // 其他信息
                        incomeRequest.setBankCardNumber(dto.getBankCardNumber());
                        incomeRequest.setBankUserName(dto.getBankUserName());

                        // 证件信息
                        incomeRequest.setIdPositive(dto.getIdPositive());
                        incomeRequest.setIdBack(dto.getIdBack());
                        incomeRequest.setHoldIdImg(dto.getHoldIdImg());

                        callback.onCallback(dto);
                    }
                }
            }
        }.showDialog(showDialog));
    }

    public static IncomeRequestEntity currentIncome() {
        return request;
    }

    public static boolean needQueueBaseRule() {
        return VnUtil.isEmpty(baseRuleList);
    }

    public static boolean needQueueIdRule() {
        return VnUtil.isEmpty(idRuleList);
    }

    public static void setBaseRuleList(List<PropertyRuleEntity> list) {
        baseRuleList = list;
    }

    public static void setIdRuleList(List<PropertyRuleEntity> list) {
        idRuleList = list;
    }

    public static PropertyRuleEntity findBaseRule(String name) {
        if (baseRuleList == null) return null;
        for (PropertyRuleEntity bean : baseRuleList) {
            if (name.equals(bean.getName())) return bean;
        }
        return null;
    }

    public static PropertyRuleEntity findIdRule(String name) {
        if (idRuleList == null) return null;
        for (PropertyRuleEntity bean : idRuleList) {
            if (name.equals(bean.getName())) return bean;
        }
        return null;
    }

    public static String checkContactsPhone(String phone) {
        PropertyRuleEntity rule = RequestHelper.findBaseRule("phone");
        if (rule != null) {
            RuleNotEmptyEntity notEmpty = rule.getNotEmpty();
            if (notEmpty != null) {
                if (VnUtil.isEmpty(phone)) {
                    return notEmpty.getMessage();
                }
            }

            RuleStringLengthEntity stringLength = rule.getStringLength();
            if (stringLength != null) {
                int size = phone.length();
                if (size < stringLength.getMin() || size > stringLength.getMax()) {
                    return stringLength.getMessage();
                }
            }

            RuleRegexpEntity regexp = rule.getRegexp();
            if (regexp != null) {
                if (!phone.matches(regexp.getRegexp())) {
                    return regexp.getMessage();
                }
            }
        } else {
            if (VnUtil.isEmpty(phone)) {
                return VnApp.getStr(R.string.error_phone_empty);
            }

            int len = phone.length();
            if (!(len == 11 || len == 12)) {
                return VnApp.getStr(R.string.error_phone_empty);
            }
        }

        return null;
    }

    public static void setFinancialProducts(List<RFinancialProductDto> list) {
        products = list;
    }

    public static EmergencyContactsEntity toEmergencyContactsByDto(REmergencyContactDto dto) {
        EmergencyContactsEntity bean = new EmergencyContactsEntity();
        bean.setContactName(dto.getContactName());
        bean.setContactOrder(String.valueOf(dto.getContactOrder()));
        bean.setContactPhone(dto.getContactPhone());
        bean.setContactRealName(dto.getContactRealName());
        if (dto.getContactRelation() != null) {
            bean.setContactRelation(dto.getContactRelation().getValue());
        }
        return bean;
    }

    public static void requestApplyActivity(Activity activity,
                                            String commodityName,
                                            String commodityNum) {
        // 启动定位
        LocationHelper.getInstance().requestLocation();

        // 上传关键信息
        DeviceApi.uploadKeyInfo(new ReqCallback() {
            @Override
            public void callback(ReqResult value) {

            }
        });

        request = new IncomeRequestEntity();
        currentCommodityNum = commodityNum;
        currentCommodityName = commodityName;
        AppConfigEntity config = VnContext.instance().getAppConfig();
        if (config != null) {
            int state = config.getUserState();
            // 1首贷 2复贷 3复贷资料过期
            if (state == 1 || state == 3) {
                VnUIManager.nextActivity(activity, Step1Activity.class);
            } else if (state == 2) {
                VnUIManager.nextFinancialProduct(activity, false);
            }
        } else {
            VnUIManager.nextActivity(activity, Step1Activity.class);
        }
    }

    public interface OnCustomerDataCallback {

        void onCallback(RCustomerDataDto dto);
    }
}
